package com.pioneer.web.stock.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pioneer.common.exception.CustomException;
import com.pioneer.web.book.domain.Book;
import com.pioneer.web.book.mapper.BookMapper;
import com.pioneer.web.stock.domain.StoInc;
import com.pioneer.web.stock.domain.StoIncBody;
import com.pioneer.web.stock.mapper.StoIncreaseBodyMapper;
import com.pioneer.web.stock.mapper.StoIncreaseMapper;
import com.pioneer.web.stock.service.IStoIncService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;

/**
 * @author aom-star@outlook.com
 * @description 针对表【sto_increase】的数据库操作Service实现
 * @createDate 2025-05-25 14:07:32
 */
@Service
public class StoIncServiceImpl extends ServiceImpl<StoIncreaseMapper, StoInc>
        implements IStoIncService {
    @Resource
    private StoIncreaseMapper stoIncMapper;

    @Resource
    private BookMapper bookMapper;

    @Resource
    private StoIncreaseBodyMapper stoIncBodyMapper;

    public StoInc select(Long incId) {
        StoInc stoInc = stoIncMapper.selectById(incId);
        if (stoInc == null) {
            throw new CustomException("该损耗单据不存在喵");
        }
        LambdaQueryWrapper<StoIncBody> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StoIncBody::getIncreaseId, incId);
        List<StoIncBody> bodyList = stoIncBodyMapper.selectList(queryWrapper);
        stoInc.setBodyList(bodyList);
        return stoInc;
    }

    @Override
    public int insertInc(StoInc inc) {
        List<StoIncBody> bodyList = inc.getBodyList();
        if (bodyList.isEmpty()) {
            throw new CustomException("损耗明细为空喵");
        }
        inc.setStatus("0");
        dealBodyList(bodyList);
        getBaseMapper().insert(inc);
        bodyList.forEach(body -> body.setIncreaseId(inc.getIncreaseId()));
        return stoIncBodyMapper.insertBatch(bodyList);
    }

    @Override
    public int updateInc(StoInc inc) {
        StoInc stoInc = getById(inc.getIncreaseId());
        if (!"0".equals(stoInc.getStatus())){
            throw new CustomException("只有状态为待确认的数据才可以修改");
        }
        List<StoIncBody> bodyList = inc.getBodyList();
        if (CollUtil.isEmpty(bodyList)) {
            throw new CustomException("子信息不能为空");
        }
        dealBodyList(bodyList);
        getBaseMapper().updateById(inc);

        // 删除旧的信息
        LambdaQueryWrapper<StoIncBody> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StoIncBody::getIncreaseId, inc.getIncreaseId());
        stoIncBodyMapper.delete(wrapper);

        return stoIncBodyMapper.insertBatch(bodyList);
    }

    @Override
    public boolean deleteStoInc(List<Long> stoIncIds) {
        List<StoInc> stoIncList = listByIds(stoIncIds);
        if (stoIncList.isEmpty()) {
            throw new CustomException("删除数据不存在喵");
        }
        for (StoInc stoInc : stoIncList) {
            if (!"0".equals(stoInc.getStatus())) {
                throw new CustomException("只有状态为待确认数据才可以删除");
            }
        }
        LambdaQueryWrapper<StoIncBody> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(StoIncBody::getIncreaseId, stoIncIds);
        stoIncBodyMapper.delete(wrapper);
        return removeByIds(stoIncIds);
    }

    @Override
    public boolean approveStoInc(StoInc inc) {
        StoInc stoInc = getById(inc.getIncreaseId());
        if (stoInc == null) {
            throw new CustomException("该数据不存在喵");
        }
        if ("1".equals(stoInc.getStatus())) {
            throw new CustomException("该数据已确认喵");
        }

        // 查询所有补充明细
        LambdaQueryWrapper<StoIncBody> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StoIncBody::getIncreaseId, inc.getIncreaseId());
        List<StoIncBody> bodyList = stoIncBodyMapper.selectList(queryWrapper);
        if (CollUtil.isEmpty(bodyList)) {
            throw new CustomException("没有明细，无法入库喵");
        }

        // 遍历入库明细，更新库存
        for (StoIncBody body : bodyList) {
            BigDecimal number = body.getNumber();

            Long bookId = body.getBookId();
            Book book = bookMapper.selectById(bookId);

            Book updateBook = new Book();
            updateBook.setId(bookId);
            updateBook.setStock(book.getStock().add(number));
            updateBook.setTotal(book.getTotal().add(number));
            boolean ret = (bookMapper.updateById(updateBook) > 0);
            if (!ret) {
                throw new CustomException("更新图书失败");
            }
        }

        StoInc update = new StoInc();
        update.setStatus("1");
        update.setIncreaseId(inc.getIncreaseId());
        return updateById(update);
    }

    private void dealBodyList(List<StoIncBody> bodyList) {
        for (int i = 0; i < bodyList.size(); i++) {
            if (bodyList.get(i).getBookId() == null){
                throw new CustomException("图书序号不能为空喵");
            }
            if (bookMapper.selectById(bodyList.get(i).getBookId()) == null) {
                throw new CustomException("第" + (i+1) + "行图书不存在喵");
            }
            if (bodyList.get(i).getNumber().equals(BigDecimal.ZERO) || bodyList.get(i).getNumber() == null) {
                throw new CustomException("数量不能为空喵");
            }
        }
    }
}




